import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Select,
	DatePicker,
	message,
	Spin,
} from 'antd'
import React, {useState, useEffect} from 'react'
import {history} from 'umi'
import moment from 'moment'
import styles from './index.less'
import {getAllParking} from '@/service/storage/archives'
import {getDict} from '@/service/common/dict'
import MaterialTable from '../../components/MaterialTable'
import Modal from '@/components/Modal'
import {editWarehouseout, warehouseoutInfo} from '@/service/storage/outDepot'
import VehicleTable from '../../components/VehicleTable'
import OperationRecord from '@/components/OperationRecord'
import {getTableList} from '@/service/purchase/plan'

const {TextArea} = Input

const edit = (props: any) => {
	const {query} = props.location
	const [loading, setLoading] = useState(false)
	const [basicsForm] = Form.useForm()
	const [type, setType] = useState<string>()
	const [outWarehouseType, setOutWarehouseType] = useState('')
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [status, setStatus] = useState<string>('1')
	const [dictData, setDictData] = useState<any>()
	const [formData, setFormData] = useState<any>({})
	const [warehouseData, setWarehouseData] = useState<any>([])
	// 调拨的公司仓库
	const [warehouseDatas, setWarehouseDatas] = useState<any>([])
	// 选择的列表数据
	const [dataList, setDataList] = useState<any>([])
	// 选中的出库仓信息
	const [outWarehouse, setOutWarehouse] = useState<any>()
	const [materialList, setMaterialList] = useState<any[]>([])
	const [btnLoading, setBtnLoading] = useState(false)
	const [procureList, setProcureList] = useState<any[]>([])
	const [valueNo, setValueNo] = useState<string>()

	// 获取采购下拉数据
	const onListFun = (value: string) => {
		getTableList({
			current: 1,
			size: 20,
			auditStatus: 1,
			planNo: value,
		}).then((res: any) => {
			if (res?.data?.records) {
				setProcureList(() => res.data.records)
			}
		})
	}
	const handleSearch = (newValue: string) => {
		if (newValue) {
			if (outWarehouseType === '1') {
				onListFun(newValue)
			} else {
				setProcureList([])
			}
		} else {
			setProcureList([])
		}
	}
	const handleChange = (newValue: string) => {
		setValueNo(newValue)
	}

	/** 获取仓库列表 */
	const getWarehouseData = () => {
		const queryData =
			query?.type === 'vehicle'
				? {
						warehouseType: '1',
				  }
				: {}
		getAllParking(queryData)
			.then((res: any) => {
				setWarehouseData(res.data)
			})
			.catch(() => {
				setWarehouseData([])
			})
	}

	useEffect(() => {
		getWarehouseData()
		getDict(
			{
				dictKeys: [
					'OUT_WAREHOUSE_STATUS',
					'OUT_WAREHOUSE_TYPE',
					'storage_large_classify',
					'storage_middle_classify',
					'Company',
				],
			},

			(res: any) => {
				setDictData(res)
			},
		)
		setLoading(true)
		if (query?.id) {
			warehouseoutInfo(query?.id)
				.then((res: any) => {
					setLoading(false)
					if (res?.success) {
						if (res?.data?.moveInCompany) {
							getAllParking({
								orgId: res?.data?.moveInCompany,
								warehouseType: '1',
							})
								.then((result: any) => {
									if (result?.success) {
										setWarehouseDatas(result.data)
									}
								})
								.catch(() => {
									setWarehouseDatas([])
								})
						}

						basicsForm.setFieldsValue({
							...res.data,
							outWarehouseTime: moment(
								res.data?.outWarehouseTime,
							),
							inWarehouse:
								res?.data?.inWarehouse === 0
									? undefined
									: res?.data?.inWarehouse,
							createTime: moment(res.data?.createTime),
						})
						setOutWarehouse({
							id: res.data?.outWarehouse,
							orgId: res?.data?.orgId,
							cityId: res?.data?.cityId,
						})
						setDataList(res?.data?.warehouseInoutGoodsList)
						setStatus(res?.data.outWarehouseStatus)
						setOutWarehouseType(res?.data.outWarehouseType)
					}
				})
				.catch((err) => {
					message.error(err)
					setLoading(false)
				})
		}
	}, [query])
	// 根据路由判断当前页面状态
	useEffect(() => {
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else {
			setType('edit')
		}
	}, [])

	const dataVerification = () => {
		const newData = [...dataList]
		materialList?.forEach((materialItem: any) => {
			dataList?.forEach(
				(item: {goodsId: any; total: number}, index: number) => {
					if (item?.goodsId === materialItem?.goodsId) {
						newData[index].total = materialItem.goodsQuantity
					}
				},
			)
		})
		setDataList(newData)
	}

	useEffect(() => {
		if (materialList?.length && dataList?.length) {
			dataVerification()
		}
	}, [materialList])

	const onSave = async () => {
		const value = await basicsForm.validateFields()
		if (value) {
			if (dataList?.length !== 0) {
				const newData = dataList.find(
					(item: {total: number; goodsQuantity: any}) =>
						item?.total < Number(item?.goodsQuantity),
				)
				if (newData) {
					message.warning(
						`${newData.goodsName}的出库数量不能大于库存数量`,
					)
				} else {
					delete value?.createTime
					delete value?.createUserName
					setFormData({
						...value,
						outWarehouseName: outWarehouse?.warehouseName,
						orgId: outWarehouse?.orgId,
						cityId: outWarehouse?.cityId,
						warehouseInoutGoodsList: dataList,
					})
					setIsModalOpen(true)
				}
			} else {
				const warn =
					query?.type === 'vehicle' ? '请选择车辆' : '请添加物料'
				message.warning(warn)
			}
		}
	}
	const onSubmit = () => {
		setBtnLoading(true)
		editWarehouseout({...formData, id: query.id})
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
				setBtnLoading(false)
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}

	return (
		<Spin spinning={loading}>
			{' '}
			<div className={styles.edit}>
				<div className={styles.title}>基础信息</div>
				<Form
					form={basicsForm}
					name="basic"
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					disabled={type === 'view'}>
					<Row gutter={12}>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="出库单号"
								name="outWarehouseNo"
								rules={[{required: true}]}>
								<Input placeholder="请输入" disabled />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="状态"
								name="outWarehouseStatus"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									allowClear
									fieldNames={{
										value: 'dictKey',
										label: 'dictValue',
									}}
									options={dictData?.OUT_WAREHOUSE_STATUS}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="出库类型"
								name="outWarehouseType"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									allowClear
									fieldNames={{
										value: 'dictKey',
										label: 'dictValue',
									}}
									onChange={(value) => {
										setOutWarehouseType(value)
										basicsForm.setFieldsValue({
											sourceDocNo: undefined,
										})
									}}
									options={dictData?.OUT_WAREHOUSE_TYPE}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item label="来源单号" name="sourceDocNo">
								{outWarehouseType === '1' ? (
									<Select
										showSearch
										value={valueNo}
										placeholder={props.placeholder}
										style={props.style}
										defaultActiveFirstOption={false}
										showArrow={false}
										filterOption={false}
										onSearch={handleSearch}
										onChange={handleChange}
										notFoundContent={null}
										options={(procureList || []).map(
											(d) => ({
												value: d.planNo,
												label: d.planNo,
											}),
										)}
									/>
								) : (
									<Input placeholder="请输入" />
								)}
							</Form.Item>
						</Col>
						{query?.type === 'vehicle' &&
						outWarehouseType === '2' ? (
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="入库仓"
									name="inWarehouse"
									rules={[{required: true}]}>
									<Select
										fieldNames={{
											value: 'id',
											label: 'warehouseName',
										}}
										showSearch
										optionFilterProp="warehouseName"
										placeholder="请选择"
										options={warehouseDatas}
									/>
								</Form.Item>
							</Col>
						) : (
							''
						)}
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="出库仓"
								name="outWarehouse"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									allowClear
									fieldNames={{
										value: 'id',
										label: 'warehouseName',
									}}
									showSearch
									optionFilterProp="warehouseName"
									disabled={
										(query?.type === 'vehicle' &&
											outWarehouseType === '2') ||
										type === 'view'
									}
									onSelect={(value: any, key: any) => {
										setOutWarehouse(key)
										setDataList([])
									}}
									options={warehouseData}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item label="提货人" name="extractMan">
								<Input placeholder="请输入" />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item label="创建时间" name="createTime">
								<DatePicker disabled placeholder="请选择" />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item label="创建人" name="createUserName">
								<Input disabled placeholder="请输入" />
							</Form.Item>
						</Col>
						{status === '2' ? (
							<>
								{' '}
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="出库时间"
										name="outWarehouseTime">
										<DatePicker
											disabled
											placeholder="请选择"
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="出库人"
										name="outWarehouseMan">
										<Input disabled placeholder="请输入" />
									</Form.Item>
								</Col>
							</>
						) : (
							''
						)}
						<Col span={16} style={{marginRight: '20px'}}>
							<Form.Item label="备注" name="remark">
								<TextArea
									maxLength={200}
									placeholder="请输入（最多200个字）"
									autoSize={{minRows: 3, maxRows: 6}}
								/>
							</Form.Item>
						</Col>
					</Row>
				</Form>
				{query?.type === 'vehicle' ? (
					<VehicleTable
						type="edit"
						edit={type === 'edit'}
						data={dataList}
						outWarehouseType={outWarehouseType}
						setDataList={setDataList}
						outWarehouse={outWarehouse}
					/>
				) : (
					<MaterialTable
						data={dataList}
						edit={type === 'edit'}
						dictData={dictData}
						outWarehouse={outWarehouse}
						materialList={materialList}
						setMaterialList={setMaterialList}
						setDataList={setDataList}
					/>
				)}
				{type === 'view' ? (
					<>
						<div className={styles.title}>操作记录</div>
						<OperationRecord
							businessId={query?.id}
							businessType={41}
						/>
					</>
				) : (
					''
				)}
				<div className={styles.wrap}>
					{type === 'view' ? (
						<Button
							onClick={() => {
								history.go(-1)
							}}>
							返回
						</Button>
					) : (
						<>
							{' '}
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => {
									onSave()
								}}>
								保存
							</Button>
							<Button
								onClick={() => {
									history.go(-1)
								}}>
								取消
							</Button>
						</>
					)}
				</div>
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				onSubmit={onSubmit}
				loading={btnLoading}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</Spin>
	)
}

export default edit
